package com.xinyu126.location.trace

import android.Manifest.permission.*
import android.os.Bundle
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import com.magical.location.client.ILocationClient
import com.xinyu126.location.trace.ui.theme.MagicalLocationTheme
import com.xinyu126.net_trace.listener.NetTraceListener
import com.xinyu126.net_trace.share.ShareActivity
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import com.magical.location.client.ILocationAble

class StartActivity : ComponentActivity() {
    private lateinit var client: ILocationClient
    var hasPermision:Boolean = false
    private lateinit var requestMultiplePermissions: ActivityResultLauncher<Array<String>>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        this.client = (application as ILocationAble).client
        val binding = StartUIModel(client)
        setContent {
            MagicalLocationTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        binding = binding,
                        this    ,
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }

        client.addListener(binding)
        client.addListener(NetTraceListener(this))

        requestMultiplePermissions = registerForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) { permissions ->

            hasPermision = permissions.all { it.value }
            if (!hasPermision) {
                showPermissionDeniedDialog()
            }
        }
        checkPermission()
    }

    fun requestPermission(){
        requestMultiplePermissions.launch(
            arrayOf(
                ACCESS_FINE_LOCATION,
                ACCESS_WIFI_STATE,
                ACCESS_COARSE_LOCATION,
                ACCESS_BACKGROUND_LOCATION,
                CHANGE_WIFI_STATE
            )
        )

    }

    private fun checkPermission(){
        arrayOf(
            ACCESS_FINE_LOCATION,
            ACCESS_WIFI_STATE,
            ACCESS_COARSE_LOCATION,
            ACCESS_BACKGROUND_LOCATION,
            CHANGE_WIFI_STATE
        ).forEach {
            if(PackageManager.PERMISSION_GRANTED!=ContextCompat.checkSelfPermission(this,it)){
                hasPermision = false
                Log.d("StartActivity","check permission fail:# $it")
            }else{
                Log.d("StartActivity","i have permission : $it")
            }
        }
    }

    private fun showPermissionDeniedDialog() {
        AlertDialog.Builder(this)
            .setTitle("需要权限")
            .setMessage("部分功能需要定位和网络权限才能使用")
            .setPositiveButton("去设置") { _, _ ->
                startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    data = Uri.fromParts("package", packageName, null)
                })
            }
            .setNegativeButton("取消", null)
            .show()
    }

//    override fun onDestroy() {
//        super.onDestroy()
//    }
}

@Composable
fun Greeting(binding: UIBindings, activity:StartActivity, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    
    Column(modifier = modifier) {
        Text(text = "Hello",color= MaterialTheme.colorScheme.surface)
        Text(text = "World",color= MaterialTheme.colorScheme.primary)
        
        // 使用 binding.states() 的值来自动切换按钮
        val isRunning = binding.states().collectAsState()
        
        Button(
            modifier = Modifier.fillMaxWidth(),
            onClick = {
                if(activity.hasPermision) {
                    if (isRunning.value) {
                        binding.stop()
                    } else {
                        binding.start()
                    }
                }else{
                    activity.requestPermission()
                }
            }
        ) {
            Text(text = if (isRunning.value) "定位服务中->停止定位" else "已停止->开始定位")
        }
        
        Button(
            modifier = Modifier.fillMaxWidth(),
            onClick = {
            context.startActivity(Intent(context, ShareActivity::class.java))
        }) {
            Text(text = "跟踪")
        }
    }
}

